function NI = init_analog(ai_channels,ao_channels,rate)
% init_analog  Initialize Ni board with analog inputs/outputs.
%    NI = init_analog(ai_channels,ao_channels,rate)
%
%  Example:
%
%       NI = init_analog(0:1, 0, 10000) % opens AI0 and AI1, and AO0 at 10 kHz
%
%
% Benvenuto Jacob, UCLouvain, Apr 2023.

persistent sess

%% Create Session Object
if ~isempty(sess)
    try
        stop(sess)
    end
    delete(sess)
end
daqreset;
sess = daq.createSession('ni');

%% Get NI Device ID (e.g.: 'Dev3')
dev = daq.getDevices;
ID = dev.ID;
    % getDevices seems to return nothing unless we add daqreset
%% Add Channels
if ~isempty(ai_channels)
    sess.addAnalogInputChannel(ID, ai_channels, 'Voltage');
end
if ~isempty(ao_channels)
    sess.addAnalogOutputChannel(ID, ao_channels, 'Voltage');
end
sess.Rate = rate;

%% Output Session Object
NI = sess;